<?php require_once(BASEPATH.'application/controllers/validaciones.php');
//Cliente
class creditos extends validaciones {
	
	
	function creditos(){
		parent::Controller(); 
		$this->load->library("rapyd");
		$this->load->library('Cuenta');
	}

	function index(){
		redirect("ventas/creditos/filteredgrid");
	}
	function filteredgrid(){
		
						
		$this->rapyd->load("datafilter","datagrid2");
		$this->rapyd->uri->keep_persistence();
		
		$link2=site_url('inventario/common/get_zona');
		$link3=site_url('inventario/common/get_estados');
				
		$filter = new DataFilter("B&uacute;squeda de Cliente");
		$select=array('a.moneda','a.cod_cli','a.idfactura','SUM(a.letras) letras','a.nombre','fecha','numero as factura','SUM(monto-impuesto) as subtotal','SUM(impuesto)impuesto','SUM(abonos) abonos','presup','vence',
			      'b.id as scli','sum(monto) as total','sum(monto-letras) as contpar',
			      '(IF((SELECT SUM(abono) FROM itpagos as c WHERE a.cod_cli=c.cod_cli AND a.moneda=c.moneda)>0,SUM(monto)-(SELECT SUM(abono) FROM itpagos as c WHERE a.cod_cli=c.cod_cli AND a.moneda=c.moneda),SUM(monto)))as resta','IF(vence > CURDATE(),0,DATEDIFF(CURDATE(),vence)) as vencio',
			      'COUNT(*) AS cant','(SUM(abonos) - SUM(letras)) as abonoscp','(IF((SELECT SUM(monto) FROM itpagos as c WHERE a.cod_cli=c.cod_cli AND a.moneda=c.moneda)>0,SUM(monto)-(SELECT SUM(monto) FROM itpagos as c WHERE a.cod_cli=c.cod_cli AND a.moneda=c.moneda),SUM(monto))) as sindef');
		$filter->db->select($select);
		$filter->db->from('smov AS a');
		$filter->db->join('scli AS b' ,'a.cod_cli=b.cliente','LEFT');
        $filter->db->where("tipo_doc IN ('FC','ND','RI')");
        $filter->db->groupby('a.cod_cli,a.moneda');	
		$filter->db->orderby('a.cod_cli');	
		
		$ano=date("Y");
        $mes=date("m");
        
        $filter->fechad = new dateonlyField('Desde', 'fechad','d/m/Y');
		$filter->fechah = new dateonlyField('Hasta', 'fechah','d/m/Y');
		$filter->fechah->size=$filter->fechad->size=12;
		$filter->fechah->operator='<=';
        //$filter->fechad->insertValue = date("Y-m-d", mktime(0, 0, 0,01, 1, $ano));
        //$filter->fechah->insertValue = date("Y-m-d", mktime(0, 0, 0,$mes+3, 1, $ano));
		$filter->fechad->clause  =$filter->fechah->clause ='where';
		$filter->fechad->db_name =$filter->fechah->db_name='a.fecha';
		$filter->fechad->operator='>=';
        
		$filter->cliente = new inputField("Codigo Cliente", "a.cod_cli");
		$filter->cliente->size=10;
		
		$filter->nombre= new inputField("Nombre de Cliente"  , "b.nombre");
		$filter->nombre->size=50;
		
		$filter->moneda = new dropdownField("Moneda", "moneda");
		$filter->moneda->style='width:200px;';
		$filter->moneda->option("","Todas las monedas" );
		$filter->moneda->options("SELECT codigo,descrip FROM moneda ORDER BY codigo");
												
		$filter->buttons("reset","search");
		$filter->build();
			
		$uri = anchor('ventas/creditos/dataedit/create/<#cod_cli#>/<#moneda#>/<#moneda#>','<#cod_cli#>');
		    	
		
		//calculo de saldos pendientes
        
        //$saldo1=$this->datasis->dameval("SELECT SUM(monto)-SUM(abonos) as resta FROM smov WHERE moneda='02' AND tipo_doc='FC'");
        //$letras1=$this->datasis->dameval("SELECT SUM(monto)-SUM(abono) as resta FROM itpagos WHERE compro='L' and moneda='02'");
        //$saldo0=$this->datasis->dameval("SELECT SUM(monto)-SUM(abonos) as resta FROM smov WHERE moneda='01'AND tipo_doc='FC'");
        //$letras0=$this->datasis->dameval("SELECT SUM(monto)-SUM(abono) as resta FROM itpagos WHERE compro='L' and moneda='01'");
        
        
        //$grid = new DataGrid2("DOLAR: Contado o Parcial: ".nformat($saldo1)." / Letras:".nformat($letras1).' / Total: '.nformat($saldo1+$letras1).' </br> SOL: &nbsp;&nbsp;&nbsp; Contado o Parcial: '.nformat($saldo0)." / Letras:".nformat($letras0).' / Total: '.nformat($saldo0+$letras0));
		$grid = new DataGrid2("");
		$grid->order_by("nombre","DESC");
        //$grid->agrupar(' ', 'nombre');
		$grid->per_page=15;  
		
		$grid->column_orderby("Cliente"             ,$uri                                              ,"cliente");
		$grid->column_orderby("Nombre"              ,"nombre","nombre"                                 ,"align='LEFT'");
		$grid->column_orderby("Moneda"              ,"moneda","moneda"                                 ,"align='center'");
		$grid->column_orderby('Sub-Total'           ,'<nformat><#subtotal#></nformat>' ,  'subtotal'   ,"align='right'");
		$grid->column_orderby('Impuesto'            ,'<nformat><#impuesto#></nformat>' ,'impuesto'     ,"align='right'");
		$grid->column_orderby('Total'               ,'<nformat><#total#></nformat>'    ,'total'        ,"align='right'");
		//$grid->column_orderby('Abonos'              ,'<nformat><#abonos#></nformat>'   ,'abonos'       ,"align='right'");
		//$grid->column_orderby('Letras'              ,'<nformat><#letras#></nformat>'   ,'letras'       ,"align='right'");
		//$grid->column_orderby('Contado/Parcial','<nformat><#abonoscp#></nformat>'   ,'abonoscp'       ,"align='right'");
		//$grid->column_orderby('Sin definir'     ,'<nformat><#sindef#></nformat>'  ,'sindef'        ,"align='right'");	
		$grid->column_orderby('Resta'               ,'<nformat><#resta#></nformat>'    ,'resta'        ,"align='right'");
		$grid->column_orderby('Cant. de  Facturas'   ,'cant' );
		 
		$grid->add("ventas/creditos/clientes/create",'Todos los Clientes');        
		$grid->totalizar('subtotal','impuesto','total','abonos','resta','letras','sindef','abonoscp');
    
		//$grid->build('datagridST');
		$grid->build();
		//echo $grid->db->last_query();
		
		$cana=$grid->recordCount;
		$grid=$grid->output;
		
		$style ='
		<style type="text/css">
		.fakeContainer { /* The parent container */
		    margin: 5px;
		    padding: 0px;
		    border: none;
		    width: 1100px; /* Required to set */
		    height: 480px; /* Required to set */
		    overflow: hidden; /* Required to set */
		}
		</style>	
		';

		$data['style']   = $style;
		$data['style']  .= style('superTables.css');
		
		IF($cana<=0){
			$data['content'] = '<div align="center">Ningun Resultado Obtenido</div>';	
		}ELSE{
			$data['content'] = $grid;		
		}


		$data['filtro']  = $filter->output;

		$data['title']   = heading("Ingresos por Cliente");
		$data['script']  = script('jquery.js');
		$data["script"] .= script('superTables.js');
		$data['head']    = $this->rapyd->get_head();

		$this->load->view('view_ventanas', $data);
	}
	function dataedit($estado,$codigoc,$moneda,$moneda2){
		
		$this->rapyd->load('dataedit');
        
		$modbus=array(
			'tabla'   =>'cpla',
			'columnas'=>array(
				'cuenta'  =>'Cuenta',
				'descrip' =>'Descripci&oacute;n',
				'ajuste'  => 'Llevar Ajuste',
				'contrapartida'  => 'Contrapartida',
				'clase'  => 'Clase',
				'costo'  => 'Costo',
				'tercero'  => 'Tercero',
				'extranjeria'  => 'Extranjeria'
				),
			'filtro'  =>array('cuenta'  =>'Cuenta','descrip'=>'Descripci&oacute;n'),
			'retornar'=>array(
				'cuenta' =>'cuenta'
				),
			'p_uri'   => array(4=>'<#i#>'),
			'titulo'  => 'Buscar Cuenta'
		);

		$btn=$this->datasis->p_modbus($modbus);

		
		$modbus_sprv=array(
			'tabla'   =>'sprv',
			'columnas'=>array(
                'cod_cli' =>'C&oacute;digo cod_cli',
                'nombre'=>'Nombre',
                'rif'=>'RIF'),
			'filtro'  =>array('cod_cli'=>'C&oacute;digo cod_cli','nombre'=>'Nombre'),
			'retornar'=>array(
                'cod_cli'=>'cod_cli',
                'rif'=>'rif',
                'nombre'=>'nombre'),
                'p_uri'   => array(4=>'<#i#>'),
			'titulo'  =>'Buscar cod_cli');

		$boton=$this->datasis->p_modbus($modbus_sprv);
		
		$cod_cli=$this->datasis->dameval("SELECT cliente FROM scli WHERE cliente='$codigoc'");
		$nombre=$this->datasis->dameval("SELECT nombre FROM scli WHERE cliente='$codigoc'");
		$rif=$this->datasis->dameval("SELECT rifci FROM scli WHERE cliente='$codigoc'");
		
		if(empty($cod_cli)){
			$cod_cli=$this->datasis->dameval("SELECT proveed FROM sprv WHERE proveed='$codigoc'");
		}
        if(empty($nombre)){
			$nombre=$this->datasis->dameval("SELECT nombre FROM sprv WHERE proveed='$codigoc'");
		}
		if(empty($rif)){
			$rif=$this->datasis->dameval("SELECT rif FROM sprv WHERE proveed='$codigoc'");
		}
        

		$edit = new DataEdit(" ", "itabonos");
        $edit->back_url = site_url('ventas/creditos/filteredgrid');    
		
		if($edit->_status=='create'){		
			$codcli=$cod_cli;			
			
		}else{		
			$codcli=$edit->_dataobject->get('cod_cli');
			if(empty($moneda))$moneda=$moneda2;
			if(empty($codcli))$codcli=$estado;
			
			
		}
		
		$mSQL="SELECT IF(a.compro='O','F',compro) compro,a.control,a.control as letra,a.banco, a.id,a.serie serief,a.numero factura,
		a.moneda,cod_cli,a.tipo,dias,fecha,vence,
		observa,a.monto, a.abono, a.monto-a.abono as resta, ultiabonado 
		FROM itpagos as a 
		WHERE a.abono < a.monto AND cod_cli='$codcli' and a.moneda='$moneda' 
		ORDER BY a.monto DESC";
		
        
        //Informacion de cod_cli

        
		$edit->pre_process('insert' ,'_pre_insert');
		$edit->post_process('insert','_post_insert');
        $edit->pre_process('delete' ,'_pre_delete');
		
		$edit->id = new hiddenField(" ", 'id');
		$edit->tipoe = new hiddenField(" ", 'tipoe');
		$edit->tipoe->db_name  = 'tipo';
		
		$edit->usuario = new autoUpdateField('usuario',$this->session->userdata('usuario'),$this->session->userdata('usuario'));
		    
        //$edit->tipo_doc = new  dropdownField ('Tipo','tipo_doc');
		//$edit->tipo_doc->option("001",'Abono a cuenta');
		//$edit->tipo_doc->option("002",'Anticipo a cuenta');
        //$edit->tipo_doc->style='width:180px;';
        
        $edit->fecha = new DateonlyField("Fecha", "fecha","Y-m-d");
		$edit->fecha->insertValue = date("Y-m-d");
		$edit->fecha->mode="autohide";
        $edit->fecha->rule= "required";
		$edit->fecha->size = 10;
		$edit->fecha->rule= "callback_cambio";
		
		$edit->vd = new  dropdownField ('Cobrador', 'vd');
		$edit->vd->options('SELECT vendedor, CONCAT(vendedor,\' \',nombre) nombre FROM vend ORDER BY vendedor');
		$edit->vd->style='width:200px;';
		
		$edit->recepcion = new DateonlyField("Recepci&oacute;n", "recepcion","Y-m-d");
		$edit->recepcion->insertValue = date("Y-m-d");
        $edit->recepcion->rule= "required";
		$edit->recepcion->size = 10;
        
		$edit->serie = new dropdownField("Comprobante", "serie");
		$edit->serie->option("","Seleccione comprobante" );
		$edit->serie->options("SELECT codigo, CONCAT_WS('-',codigo,descrip) AS descrip FROM bancos WHERE moneda='$moneda' OR moneda='$moneda2' ORDER BY codigo");
		$edit->serie->rule= "required";
        $edit->serie->style='width:200px;';
        $edit->serie->onchange = "numrecibo();";
        //$edit->serie->when=array('show');

		$edit->numero = new inputField("N&;mero", "numero");
		$edit->numero->size = 12;
		//$edit->numero->rule= "required";
        $edit->numero->css_class ='inputnum';
		$edit->numero->maxlength=11;
		$edit->numero->rule= "callback_chexiste";
		//$edit->numero->when=array('show');

		$edit->cod_cli = new inputField("C&oacute;digo", "cod_cli");
		$edit->cod_cli->size = 7;
		$edit->cod_cli->maxlength=5;
        $edit->cod_cli->rule= "required";
        $edit->cod_cli->readonly  = true;
        $edit->cod_cli->insertValue = $cod_cli;
        
        $edit->nombre = new inputField("Nombre", "nombre");
		$edit->nombre->size =  40;
		$edit->nombre->maxlength=80;
        $edit->nombre->insertValue = $nombre;
        $edit->nombre->readonly  = true;
    
		$edit->rif = new inputField("RUC", "rif");
		$edit->rif->size =  20;
		$edit->rif->maxlength=20; 
        $edit->rif->insertValue = $rif;
        $edit->rif->readonly  = true;
        
        $edit->condi1 = new inputField('Observaci&oacute;n', 'condi1');
		$edit->condi1->size =60;
		$edit->condi1->maxlength=50;
        
        $edit->ccosto = new  dropdownField ('Centro de Costo', 'ccosto');
        $edit->ccosto->option("0001","ADMINISTRACI&Oacute;N");
		$edit->ccosto->option('0002',"OPERACI&Oacute;N");
		$edit->ccosto->option('0003','IMPORTACI&Oacute;N'); 
		$edit->ccosto->style='width:200px;';     
        
        $edit->moneda = new dropdownField("Moneda", "moneda");
		$edit->moneda->style='width:200px;';
		$edit->moneda->options("SELECT codigo,descrip FROM moneda ORDER BY codigo");
		$edit->moneda->group = "Precios";
		//$edit->moneda->when=array('show');
		
		$fechac=$this->datasis->dameval("SELECT cambio FROM cambio WHERE fecha=CURDATE()");
		$edit->cambio = new inputField("Cambio", 'cambio');
		$edit->cambio->css_class ='inputnum';
		$edit->cambio->size      = 12;
		//$edit->cambio->insertValue=$fechac;
		$edit->cambio->onclick = "cfecha();";
		
		$edit->referen = new inputField('N&uacute;mero de Operaci&oacute;n', 'referen');
		$edit->referen->css_class ='inputnum';
		$edit->referen->size      = 20;
		$edit->referen->rule = 'required';
        
		$edit->monto = new inputField('Monto Total Cobrado', 'monto');
		$edit->monto->css_class ='inputnum';
		$edit->monto->readonly  =true;
		$edit->monto->size      = 10;
		//$edit->monto->rule     = 'required';
		
		$edit->montob = new inputField('Monto que Ingreso en Banco', 'montob');
		$edit->montob->css_class ='inputnum';
		$edit->montob->readonly  =true;
		$edit->montob->size      = 10;
		
		$edit->comibanco = new inputField('- Comisi&oacute;n de Banco', 'comibanco');
		$edit->comibanco->css_class ='inputnum';
		$edit->comibanco->size      = 10;
		$edit->comibanco->insertValue = '0';
		
		$edit->intbanco = new inputField('+ Intereses de Banco', 'intbanco');
		$edit->intbanco->css_class ='inputnum';
		$edit->intbanco->size      = 10;
		$edit->intbanco->insertValue = '0';
        
        $edit->cuenta = new inputField('Cuenta', 'cuenta');
		$edit->cuenta->size     = 12;
		$edit->cuenta->rule     = 'required';
		//$edit->cuenta->append($btn);
		$edit->cuenta->readonly  =true;
		$edit->cuenta->when=array('show');
		
		
		$edit->formap = new dropdownField("Medio de Pago", "formap");
		$edit->formap->style='width:200px;';
		$edit->formap->options("SELECT formap,nombre FROM formap ORDER BY formap");
        
		$edit->buttons('save', 'undo','delete','back');	
        $edit->build();
		
		$mSQL_1=$this->db->query($mSQL);
		$conten['result']=$mSQL_1->result();
		
		//echo $mSQL;
		$id=$edit->_dataobject->get("id");
        
        $conten['form']  =&  $edit;
        
        IF($edit->_status=='show'){
			$mSQL="SELECT a.*,b.control letra FROM cobros as a 
			JOIN itpagos as b on a.idpago=b.id WHERE itabono='$id'";
			$mSQL_1=$this->db->query($mSQL);
			$conten['result']=$mSQL_1->result();	
			$data['content'] = $this->load->view('view_smov', $conten,true);
		}else{
			$mSQL_1=$this->db->query($mSQL);
			$conten['cantmd']=$mSQL_1->num_rows();
			$conten['result']=$mSQL_1->result();	
			$data['content'] = $this->load->view('view_abonos', $conten,true);
		}
		
		$data['title']   = heading('Cobro a Cliente '.$edit->serie->value.'-'.$edit->numero->value);

		$data['style']  = style('redmond/jquery-ui-1.8.1.custom.css');
		
		$data['script']  = script('jquery.js');
		$data['script'] .= script('jquery-ui.js');
		$data['script'] .= script('plugins/jquery.numeric.pack.js');
		$data['script'] .= script('plugins/jquery.numeric.pack.js');
		$data['script'] .= script('plugins/jquery.floatnumber.js');
		$data['script'] .= script('nformat.js');

		$data['head']    = $this->rapyd->get_head();
		$this->load->view('view_ventanas', $data);
	}
	function clientes(){
		
		$this->rapyd->load('dataedit');
        
		$modbus=array(
			'tabla'   =>'cpla',
			'columnas'=>array(
				'cuenta'  =>'Cuenta',
				'descrip' =>'Descripci&oacute;n',
				'ajuste'  => 'Llevar Ajuste',
				'contrapartida'  => 'Contrapartida',
				'clase'  => 'Clase',
				'costo'  => 'Costo',
				'tercero'  => 'Tercero',
				'extranjeria'  => 'Extranjeria'
				),
			'filtro'  =>array('cuenta'  =>'Cuenta','descrip'=>'Descripci&oacute;n'),
			'retornar'=>array(
				'cuenta' =>'cuenta'
				),
			'p_uri'   => array(4=>'<#i#>'),
			'titulo'  => 'Buscar Cuenta'
		);

		$btn=$this->datasis->p_modbus($modbus);

		
		$modbus_sprv=array(
			'tabla'   =>'scli',
			'columnas'=>array(
                'cliente' =>'C&oacute;digo cod_cli',
                'nombre'=>'Nombre',
                'rifci'=>'RIF'),
			'filtro'  =>array('cliente'=>'C&oacute;digo Cliente','nombre'=>'Nombre'),
			'retornar'=>array(
                'cliente'=>'cod_cli',
                'rifci'=>'rif',
                'nombre'=>'nombre'),
                'p_uri'   => array(4=>'<#i#>'),
			'titulo'  =>'Buscar Cliente');

		$boton=$this->datasis->p_modbus($modbus_sprv);

		$edit = new DataEdit(" ", "itabonos");
        $edit->back_url = site_url('ventas/creditos/filteredgrid');    
		
		$mSQL="SELECT IF(a.compro='O','F',compro) compro,a.control,a.control as letra,a.banco, a.id,a.serie serief,a.numero factura,
		a.moneda,cod_cli,a.tipo,dias,fecha,vence,
		observa,a.monto, a.abono, a.monto-a.abono as resta, ultiabonado 
		FROM itpagos as a 
		WHERE a.abono < a.monto AND a.vence<=ADDDATE(CURDATE(),30)
		ORDER BY a.monto DESC LIMIT 244";
        
        //Informacion de cod_cli

        
		$edit->pre_process('insert' ,'_pre_insert');
		$edit->post_process('insert','_post_insert');
        $edit->pre_process('delete' ,'_pre_delete');
		
		$edit->id = new hiddenField(" ", 'id');
		$edit->tipoe = new hiddenField(" ", 'tipoe');
		$edit->tipoe->db_name  = 'tipo';
        
        $edit->fecha = new DateonlyField("Fecha", "fecha","Y-m-d");
		$edit->fecha->insertValue = date("Y-m-d");
		$edit->fecha->mode="autohide";
        $edit->fecha->rule= "required";
		$edit->fecha->size = 10;
		$edit->fecha->rule= "callback_cambio";
		
		$edit->vd = new  dropdownField ('Cobrador', 'vd');
		$edit->vd->options('SELECT vendedor, CONCAT(vendedor,\' \',nombre) nombre FROM vend ORDER BY vendedor');
		$edit->vd->style='width:200px;';
		
		$edit->recepcion = new DateonlyField("Recepci&oacute;n", "recepcion","Y-m-d");
		$edit->recepcion->insertValue = date("Y-m-d");
        $edit->recepcion->rule= "required";
		$edit->recepcion->size = 10;
        
		$edit->serie = new dropdownField("Comprobante", "serie");
		$edit->serie->option("","Seleccione comprobante" );
		$edit->serie->options("SELECT codigo, CONCAT_WS('-',codigo,descrip) AS descrip FROM bancos ORDER BY codigo");
		$edit->serie->rule= "required";
        $edit->serie->style='width:200px;';
        $edit->serie->onchange = "numrecibo();";
        //$edit->serie->when=array('show');

		$edit->numero = new inputField("N&;mero", "numero");
		$edit->numero->size = 12;
		//$edit->numero->rule= "required";
        $edit->numero->css_class ='inputnum';
		$edit->numero->maxlength=11;
		$edit->numero->rule= "callback_chexiste";
		//$edit->numero->when=array('show');

		$edit->cod_cli = new inputField("C&oacute;digo", "cod_cli");
		$edit->cod_cli->size = 7;
		$edit->cod_cli->maxlength=5;
        $edit->cod_cli->rule= "required";
        $edit->cod_cli->readonly  = true;
        $edit->cod_cli->append($boton);
        
        $edit->nombre = new inputField("Nombre", "nombre");
		$edit->nombre->size =  40;
		$edit->nombre->maxlength=80;
        $edit->nombre->readonly  = true;
    
		$edit->rif = new inputField("RUC", "rif");
		$edit->rif->size =  20;
		$edit->rif->maxlength=20; 
        $edit->rif->readonly  = true;
        
        $edit->condi1 = new inputField('Observaci&oacute;n', 'condi1');
		$edit->condi1->size =60;
		$edit->condi1->maxlength=50;
        
        $edit->ccosto = new  dropdownField ('Centro de Costo', 'ccosto');
        $edit->ccosto->option("0001","ADMINISTRACI&Oacute;N");
		$edit->ccosto->option('0002',"OPERACI&Oacute;N");
		$edit->ccosto->option('0003','IMPORTACI&Oacute;N'); 
		$edit->ccosto->style='width:200px;';     
        
        $edit->moneda = new dropdownField("Moneda", "moneda");
		$edit->moneda->style='width:200px;';
		$edit->moneda->options("SELECT codigo,descrip FROM moneda ORDER BY codigo");
		$edit->moneda->group = "Precios";
		//$edit->moneda->when=array('show');
		
		$fechac=$this->datasis->dameval("SELECT cambio FROM cambio WHERE fecha=CURDATE()");
		$edit->cambio = new inputField("Cambio", 'cambio');
		$edit->cambio->css_class ='inputnum';
		$edit->cambio->size      = 12;
		//$edit->cambio->insertValue=$fechac;
		$edit->cambio->onclick = "cfecha();";
		
		$edit->referen = new inputField('N&uacute;mero de Operaci&oacute;n', 'referen');
		$edit->referen->css_class ='inputnum';
		$edit->referen->size      = 20;
		$edit->referen->rule = 'required';
        
		$edit->monto = new inputField('Monto Total Cobrado', 'monto');
		$edit->monto->css_class ='inputnum';
		$edit->monto->readonly  =true;
		$edit->monto->size      = 10;
		//$edit->monto->rule     = 'required';
		
		$edit->montob = new inputField('Monto que Ingreso en Banco', 'montob');
		$edit->montob->css_class ='inputnum';
		$edit->montob->readonly  =true;
		$edit->montob->size      = 10;
		
		$edit->comibanco = new inputField('- Comisi&oacute;n de Banco', 'comibanco');
		$edit->comibanco->css_class ='inputnum';
		$edit->comibanco->size      = 10;
		$edit->comibanco->insertValue = '0';
		
		$edit->intbanco = new inputField('+ Intereses de Banco', 'intbanco');
		$edit->intbanco->css_class ='inputnum';
		$edit->intbanco->size      = 10;
		$edit->intbanco->insertValue = '0';
        
        $edit->cuenta = new inputField('Cuenta', 'cuenta');
		$edit->cuenta->size     = 12;
		$edit->cuenta->rule     = 'required';
		//$edit->cuenta->append($btn);
		$edit->cuenta->readonly  =true;
		$edit->cuenta->when=array('show');
		
		
		$edit->formap = new dropdownField("Medio de Pago", "formap");
		$edit->formap->style='width:200px;';
		$edit->formap->options("SELECT formap,nombre FROM formap ORDER BY formap");
        
		$edit->usuario = new autoUpdateField('usuario',$this->session->userdata('usuario'),$this->session->userdata('usuario'));

        $edit->buttons('save', 'undo','delete','back');	
        $edit->build();
		
		$mSQL_1=$this->db->query($mSQL);
		$conten['result']=$mSQL_1->result();
		
		//echo $mSQL;
		$id=$edit->_dataobject->get("id");
        
        $conten['form']  =&  $edit;
        
        IF($edit->_status=='show'){
			$mSQL="SELECT a.*,b.control letra FROM cobros as a 
			JOIN itpagos as b on a.idpago=b.id WHERE itabono='$id'";
			$mSQL_1=$this->db->query($mSQL);
			$conten['result']=$mSQL_1->result();	
			$data['content'] = $this->load->view('view_smov', $conten,true);
		}else{
			$mSQL_1=$this->db->query($mSQL);
			$conten['cantmd']=$mSQL_1->num_rows();
			$conten['result']=$mSQL_1->result();	
			$data['content'] = $this->load->view('view_abonos', $conten,true);
		}
		
		$data['title']   = heading('Cobro a Cliente '.$edit->serie->value.'-'.$edit->numero->value);

		$data['style']  = style('redmond/jquery-ui-1.8.1.custom.css');
		
		$data['script']  = script('jquery.js');
		$data['script'] .= script('jquery-ui.js');
		$data['script'] .= script('plugins/jquery.numeric.pack.js');
		$data['script'] .= script('plugins/jquery.numeric.pack.js');
		$data['script'] .= script('plugins/jquery.floatnumber.js');
		$data['script'] .= script('nformat.js');

		$data['head']    = $this->rapyd->get_head();
		$this->load->view('view_ventanas', $data);
	}
	function chexiste($codigo){
		
		$numero=$this->input->post('numero');
		$serie =$this->input->post('serie');
		
		$numero =str_pad($numero, 11, "0", STR_PAD_LEFT);
		$serie  =str_pad($serie, 3, "0", STR_PAD_LEFT);
		
		$chek=$this->datasis->dameval("SELECT COUNT(*) FROM itabonos WHERE serie='$serie' AND numero='$numero'");
		if ($chek > 0){
			$this->validation->set_message('chexiste',"El numero de comprobante $numero ya se encuetra registrado");
			return FALSE;
		}else {
		 return TRUE;
		}
	}
	function _pre_insert($do){
		
        $cod_cli  =$do->get('cod_cli');
		$fecha    =$do->get('fecha');
		$serie    =$do->get('serie');
		$intbanco =$do->get('intbanco');
		$comibanco=$do->get('comibanco');
		$cambiom  =$do->get('cambio');
        
        //actualiza al cambio segun fecha
        
        $cuenta=$this->datasis->dameval("SELECT cuenta FROM bancos WHERE codigo='$serie'");
        $moneda=$this->datasis->dameval("SELECT moneda FROM bancos WHERE codigo='$serie'");
        
        IF($cambiom>0){	
			$cambio=$cambiom;
		}else{
			$cambio=$this->datasis->dameval("SELECT cambio FROM cambio WHERE fecha='$fecha'");
		}
        
        $do->set('cambio',$cambio);
        $do->set('moneda',$moneda);
        $do->set('cuenta',$cuenta);
        $do->set('tipo','AB');           
        		 
        $i=$o=$totalg=0;
        
        $pago     = $this->input->post('pago');
        $cant     = $this->input->post('cant'); 
        $monto    = $this->input->post('monto'); 
        $dfmoneda = $this->input->post('dfmoneda');
        
        $tsoles   = $this->input->post('smonto');
        $tsolesb  = $this->input->post('smontob');
        $tdolar   = $this->input->post('monto');
        $tdolarb  = $this->input->post('montob');
        
		//$monto=100;
        //$dfmoneda='N';
        
        while($o<$cant){
			
            $array=array('0'=>$pago[$i]);
        
			IF($pago[$i]>0){
				$totalg+=$pago[$i];
				//echo 'pago: '.$pago[$i].'</br>';
			}
            $i++;
			$o++;
        
		}
        
        //$totalg=5;$pago,$cant,$monto,$dfmoneda
        
        if (($tsoles<=0)||($tdolar<=0)){
			echo "<span style='color:red' align='center'>Debe ingresar una cantidad mayor a 0,00</span>";
			$this->validation->set_message('pre_insert',"Error al ingresar informacion , debe registrar un pago mayor a 0,00");
			return FALSE;
		}else {
                        
            IF($moneda=='01'){
                $monto=$tsoles;
                $montob=$tsolesb;
            }else{
                $monto=$tdolar;
                $montob=$tdolarb;
            }
            
			//$tot=(($monto+$intbanco)-$comibanco);
			
			$do->set('monto',$monto);
			$do->set('montob',$montob);
			return TRUE;
		}
                			
		
		return true;
	}
    function _pre_delete($do){
		
		
        $id=$do->get('id');
        $tipo=$do->get('tipo');
        
        //echo $id;
        $cod_cli =$do->get('cod_cli');
        $numero  =$do->get('numero');
        $id_rein =$do->get('id_rein');
        
        $mSQL_1=$this->db->query("SELECT monto, idpago, itabono, id, cod_cli,  numero,serie FROM cobros WHERE itabono='$id'");
             
        foreach($mSQL_1->result() as $items ){
            
            $this->db->query("UPDATE smov SET abonos=abonos-'$items->monto' WHERE cod_cli='$items->cod_cli' AND numero='$items->numero'");
            
            $mSQL_2=$this->db->query("UPDATE itpagos SET abono=abono-'$items->monto' WHERE cod_cli='$items->cod_cli' AND id='$items->idpago'");      
			//$mSQL_3=$this->db->query("UPDATE letras  SET abono=abono-'$items->monto' WHERE cliente='$items->cod_cli' AND factura='$items->factura' AND serief='$items->serief' AND idpago='$items->idpago'");          
            
		}
        
        
        $mSQL_2=$this->db->query("DELETE FROM cobros WHERE itabono='$id'");
        $mSQL_3=$this->db->query("DELETE FROM bmov WHERE idabono='$id' AND clipro='C'");
        $mSQL_4=$this->db->query("DELETE FROM smov WHERE transac='$id' AND tipo_doc='$tipo'");
        
        //$abono=$this->datasis->dameval("SELECT abono FROM itpagos WHERE id_rein='$id_rein'");
        //$this->db->query("update itppro set aplica=aplica-'$abono' where id='$id_rein'");
        
		logusu('ITABONOS',"COBRO al cliente $cod_cli numero $numero ELIMINADO");
	}
	function _post_insert($do){
		
		$serie=$do->get('serie');
		$numero=$do->get('numero');
        $cod_cli=$do->get('cod_cli');
        $monto=$do->get('monto');
        $montob=$do->get('montob');
        $tipo_doc=$do->get('tipo_doc');
        $banco=$do->get('banco');
        $referen=$do->get('referen');
        $fecha=$do->get('fecha');
        $condi1=$do->get('condi1');
        $formap=$do->get('formap');
        $moneda=$do->get('moneda');
        $nombre=$do->get('nombre');
        $id=$do->get('id');
        $id_rein=$do->get('id_rein');
        $intbanco=$do->get('intbanco');
        $comibanco=$do->get('comibanco');
        $usuario=$this->session->userdata['usuario'];
        
        $cajero=1;
                 
        //insertar registro en movimientos de bancos bancos
            
        $mSQL=$this->db->query("INSERT INTO bmov(banco,numero,formap,referencia,monto,fecha,observacion,cajero,idabono,recepcion,usuario,clipro,intbanco,comibanco)
                                         VALUES('$serie','$numero','$formap','$referen','$montob','$fecha','$condi1','$cajero','$id','$fecha','$usuario','C','$intbanco','$comibanco')");
                                         		
		$mSQL_3=$this->db->query("INSERT INTO smov (moneda,tipo_doc,serie,numero,fecha,cod_cli,  nombre, monto ,  usuario,transac,abonos,vence)
                                            VALUES('$moneda','AB','$serie','$numero','$fecha','$cod_cli','$nombre','$monto','$usuario','$id','$monto','$fecha')");   
   
		
		$i=$o=$totalg=0;
        
        $idp     = $this->input->post('idp');
        $pago    = $this->input->post('pago');
        $cant    = $this->input->post('cant');      		
			
		//echo $cant;
		while($o<$cant){
            
            $cliente=$this->datasis->dameval("SELECT cod_cli FROM itpagos WHERE id='$idp[$i]'");
            $factura=$this->datasis->dameval("SELECT numero FROM itpagos WHERE id='$idp[$i]'");
            $serie=$this->datasis->dameval("SELECT serie FROM itpagos WHERE id='$idp[$i]'");
            $tipo=$this->datasis->dameval("SELECT tipo FROM itpagos WHERE id='$idp[$i]'");
             
            $mSQL_2=$this->db->query("UPDATE itpagos SET abono=abono+'$pago[$i]',ultiabonado='$pago[$i]' WHERE cod_cli='$cliente' AND id='$idp[$i]'");
               
            IF($pago[$i]>0){
            
				$mSQL_1=$this->db->query("INSERT INTO cobros (tipo,serie,numero,cod_cli,monto,idpago,itabono)VALUES('$tipo','$serie','$factura','$cliente','$pago[$i]','$idp[$i]','$id');");
				
				//echo '$idp[$i]';
				$this->_abonos($idp[$i]);
				
			
			}
			
                       
            $i++;
			$o++;
		}    
        //$abono=$this->datasis->dameval("SELECT fabono FROM itpagos WHERE id_rein='$id_rein'");
        //$this->db->query("update itppro set aplica=aplica+'$abono' where id='$id_rein'");
		//$this->_abonos($id);
		logusu('itabonos',"COBRO al cliente $cliente numero $numero CREADO");
		
	}
	function _abonos($idpago){
		
		if(empty($idpago)){
			
		echo "Ocurrio un Error, comuniquese con soporte el registro no fue guardado exitosamente";
		
		}else{
			
		//1.Suma abonos de cobros en itpagos
		$abono=$this->datasis->dameval("SELECT SUM(monto) FROM cobros WHERE idpago='$idpago'");
		$this->db->query("UPDATE itpagos SET abono=$abono WHERE id='$idpago'");
					
		//2. suma itpagos en smov si no son letras
		
		$tipo=$this->datasis->dameval("SELECT COUNT(*) FROM itpagos WHERE id='$idpago'AND compro='O'");
		
		IF($tipo>0){
			
			$transac=$this->datasis->dameval("SELECT transac FROM itpagos WHERE id='$idpago' AND compro='O'");
			$contado=$this->datasis->dameval("SELECT SUM(abono) FROM itpagos WHERE transac='$transac' AND compro='O'");
			$letras=$this->datasis->dameval("SELECT SUM(monto) FROM letras WHERE transac='$transac' AND tipo NOT IN ('CONTADO','LIBRE')");
			$tot=$letras+$contado;
			$this->db->query("UPDATE smov SET abonos='$tot',letras='$letras' WHERE transac='$transac'");
		}
		
		}

	}
	function arregla(){
		
		$query=$this->db->query("SELECT idpago FROM cobros");
        
        foreach($query->result() as $items ){
		
			$abono=$this->datasis->dameval("SELECT SUM(monto) FROM cobros WHERE idpago='$items->idpago'");
			$this->db->query("UPDATE itpagos SET abono=$abono WHERE id='$items->idpago'");
			
		}
		
		$query=$this->db->query("SELECT transac FROM smov");
        
        foreach($query->result() as $items ){
		
			$abono=$this->datasis->dameval("SELECT SUM(abono) FROM itpagos WHERE transac='$items->transac' AND compro='O'");
						
			$letras=$this->datasis->dameval("SELECT SUM(monto) FROM letras WHERE transac='$items->transac' AND tipo NOT IN ('CONTADO','LIBRE')");
			
			$tot=$letras+$abono;
			
			$this->db->query("UPDATE smov SET abonos='$tot' WHERE transac='$items->transac'");
		}
			
	
	}
}
?>
